<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j shop-contianer page-shop-index page-shop-prod-list">
    <div class="shop-index">
      <div class="shop-head">
        <div class="shop-logo">
          <div class="img">
            <img-show :src="shopInfo.shopLogo" />
          </div>
          <div class="text">
            <div class="name">
              {{ shopInfo.shopName }}
            </div>
            <div class="operation">
              <div
                v-if="shopInfo.shopId === 1"
                class="self"
              >
                {{ $t('shopInfo.selfShop') }}
              </div>
              <div
                v-else
                class="self"
              >
                {{ shopInfo.type === 1 ? $t('shopInfo.preferredStores') : $t('shopInfo.generalStore') }}
              </div>
              <div
                class="favourite"
                :class="{ active: isCollection }"
                @click="shopCollection()"
              >
                <i class="icon" />
                {{ isCollection ? $t('shopInfo.followed') : $t('shopInfo.follow') }}
              </div>
            </div>
          </div>
        </div>
        <div class="shop-news">
          <div class="news-tit">
            <div class="tit">
              {{ $t('storeAnnouncement') }}
            </div>
            <div
              v-if="noticeList.length"
              class="more"
              @click="toNewsList"
            >
              {{ $t('more') }}&nbsp;&nbsp;
            </div>
          </div>
          <div
            v-if="noticeList.length"
            class="news-list-con"
          >
            <div
              v-for="(news, index) in noticeList"
              :key="index"
              class="news-item"
              @click="toNewsDet(news.id)"
            >
              {{ news.title }}
            </div>
          </div>
          <div
            v-else
            class="news-empty"
          >
            {{ $t('shopInfo.noAnnouncement') }}
          </div>
        </div>
      </div>
      <div class="shop-menu">
        <div class="menu-box">
          <div class="menu-list">
            <div class="menu">
              <a
                href="javascript:void(0);"
                class="menu-link"
                @click="homePage"
              >{{ $t('shopInfo.homePage') }}</a>
            </div>
            <div class="menu all-category">
              <a
                href="javascript:void(0);"
                class="menu-link"
                @click="getProdListByCategory()"
              >{{ $t('shopInfo.allCategories') }}</a>
              <div class="menu-wrap">
                <div
                  v-for="category in categoryList"
                  v-show="category.categoryId"
                  :key="category.categoryId"
                  class="wrap-item"
                >
                  <div class="item-tit">
                    <a
                      href="javascript:void(0);"
                      @click="getProdListByCategory(category.categoryId)"
                    >{{ category.categoryName }}</a>
                  </div>
                </div>
                <div
                  v-show="categoryList.length===0"
                  class="item-tit-no"
                >
                  {{ $t('shopInfo.noData') }}
                </div>
              </div>
            </div>
            <div
              v-for="category in categoryList"
              :key="category.categoryId"
              class="menu"
            >
              <a
                href="javascript:void(0);"
                class="menu-link"
                @click="getProdListByCategory(category.categoryId)"
              >{{ category.categoryName }}</a>
            </div>
          </div>
          <div class="shop-search">
            <input
              v-model="prodName"
              type="text"
              class="s-input"
            >
            <input
              type="button"
              :value="$t('shopInfo.search')"
              class="s-btn"
              @click="getSearchProdPage(1)"
            >
          </div>
        </div>
      </div>
      <!-- /banner -->
      <div class="content">
        <div class="shop-content">
          <div
            v-if="prodList.length > 0"
            class="tit"
          >
            <span class="bg-l" />
            {{ categoryName ? categoryName : $t('shopInfo.hotProducts') }}
            <span class="bg-r" />
          </div>
          <div class="goods-list">
            <div class="list-con">
              <!-- 商品 -->
              <div
                v-for="prod in prodList"
                :key="prod.prodId"
                class="item"
              >
                <div
                  class="goods-img"
                  @click="toProdDetail(prod.prodId)"
                >
                  <img-show :src="prod.pic" />
                </div>
                <div
                  class="goods-msg"
                  @click="toProdDetail(prod.prodId)"
                >
                  <span
                    v-if="prod.shopId === 1"
                    class="activity-sign"
                  >{{ $t('prodDetail.selfEmployed') }}</span>
                  <span
                    v-if="(prod.prodType === 1 || prod.prodType === 2) && prod.activityPrice && prod.activityInProgress"
                    class="activity-sign"
                  >
                    {{ prod.prodType === 2 ? $t('prodDetail.prodType3') : `${prod.groupActivitySearchVO?.groupNumber + $t('index.join')}` }}
                  </span>
                  {{ prod.prodName }}
                </div>
                <div class="goods-price">
                  <div class="price">
                    ￥
                    <span class="big">{{ parsePrice(prod.price)[0] }}.{{
                      parsePrice(prod.price)[1]
                    }}</span>
                  </div>
                </div>
              </div>
            </div>
            <!-- 商品 -->
            <empty-all-tips
              v-if="isLoaded && prodList.length < 1"
              :text="prodList.length < 1 && shopInfo.shopStatus === 1 ? $t('sorryNoRelatedProducts') : $t('collection.storeReviewTips4')"
              :back="prodList.length < 1 && shopInfo.shopStatus === 1 ? $t('lookAtOther') : $t('shopInfo.mallHome')"
              :back-path="backPath"
              :ex-back="prodList.length < 1 && shopInfo.shopStatus === 1 ? $t('shopInfo.mallHome') : ''"
            />
          </div>
          <!-- 全部 -->
          <br>
          <div class="goods-list">
            <!-- 页码 -->
            <pagination
              v-model="current"
              :pages="pages"
              @change-page="getSearchProdPage"
            />
            <!-- /页码 -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import { ElMessage } from 'element-plus'
const route = useRoute()
const router = useRouter()
const langStore = useLanguageStore()
const shopCategoryStore = useShopCategoryStore()

// 监听id，要是发生变化就重新请求数据
watch(() => route.query, (newVal, oldVal) => {
  // 路由变话页面刷新
  if (newVal.sid === oldVal.sid) {
    langStore.handleShopRouter(newVal)
    return
  }
  location.reload()
})

const backPath = computed(() => {
  return {
    path: '/shop-index',
    query: {
      sid: route.query.sid || 0
    }
  }
})

const current = ref(Number(route.query.c) || 1)
const shopId = ref(route.query.sid || 0)
onMounted(() => {
  document.title = $t('index.shop') + $t('products')
  getPageData(route.query)
  handleShopStatus()
  getInfo()
  if (!shopId.value) {
    ElMessage({
      message: $t('userCenter.theStoreOffline'),
      duration: 1000,
      type: 'warning'

    })
  }
})

const categoryId = ref(null)
const prodName = ref('')
/**
 * pn: 商品名称
 * cid: 店铺分类id
 * sid: 店铺id
 * sort: 根据默认(0)/销量(1)/价格(2)排序
 * size: 每页的数据数量
 * ob: 0正序 1倒序
 * c: 当前第几页
 */
const getPageData = (query = {}) => {
  getProdPage(query)
  getCategoryList(query)
  getShopInfo(query)
  getNoticeList(query)
  if (Cookie.get('bbcToken')) {
    getUserCollection()
  }
  categoryId.value = query.cid ? Number(query.cid) : null
  prodName.value = query.pn
  current.value = Number(query.c) || Number(route.query.c) || 1
}

const isLoaded = ref(false)
const prodList = ref([])
const pages = ref(null)
const getProdPage = (query) => {
  isLoaded.value = false
  http.get(Number(query.st) === 4 ? '/coupon/prodListByCouponId' : '/search/page',
    {
      // 商品列表
      params: {
        sort: 12,
        size: 20,
        current: query.c ? query.c : 1,
        shopId: query.sid,
        couponId: query.couponId || '',
        keyword: query.pn || null,
        shopCategoryId: query.cid || '',
        isAllProdType: true,
        isActive: Number(query.st) !== 4 ? 1 : undefined // 过滤掉活动商品
      }
    }
  ).then(({ data }) => {
    prodList.value = data.records[0]?.products || []
    pages.value = data.pages
    isLoaded.value = true
  })
}

const categoryList = ref([])
const categoryName = ref('')
const getCategoryList = (query) => {
  http.get('/category/categoryInfo', {
    // 店铺商品分类
    params: {
      shopId: query.sid,
      parentId: 0
    }
  }).then(({ data }) => {
    shopCategoryStore.SET_SHOPCATEGROY(data.categoryInfo)
    categoryList.value = data.categoryInfo
    const curCategory = data.categoryInfo.find(el => Number(el.categoryId) === Number(query.cid))
    categoryName.value = curCategory ? curCategory.categoryName : ''
  })
}

const shopInfo = ref({})
const getShopInfo = (query) => {
  http.get('/shop/headInfo', {
    // 店铺头部信息
    params: {
      shopId: query.sid
    }
  }).then(({ data }) => {
    shopInfo.value = data
  })
}

const noticeList = ref([])
const getNoticeList = (query) => {
  let path = '/notice/noticeList/'
  if (Cookie.get('bbcToken')) {
    path = '/p/notice/noticeList/'
  }
  http.get(path + query.sid, {
    // 店铺公告
    params: {
      current: 1, // 当前页
      size: 2
    }
  }).then(({ data }) => {
    noticeList.value = data.records || []
  })
}

/**
 * 店铺状态处理
 */
const handleShopStatus = () => {
  const shopStatus = shopInfo.value.shopStatus
  // 未开通/已删除
  if (shopStatus === -1) {
    ElMessage({
      type: 'warning',
      message: $t('collection.storeReviewTips2'),
      duration: 1000,
      onClose: () => {
        router.push({ path: '/' })
      }
    })
    return
  }
  // 停业中
  if (shopStatus === 0) {
    const contractStartTime = new Date(shopInfo.value.contractStartTime).getTime()
    const contractEndTime = new Date(shopInfo.value.contractEndTime).getTime()
    const today = new Date().getTime()
    // 1、店铺状态为0(停业中)时，当店铺未到签约开始时间，用户进入店铺提示：商家尚未营业
    if (today < contractStartTime) {
      ElMessage({
        type: 'warning',
        message: $t('collection.storeReviewTips4'),
        duration: 1000,
        onClose: () => {
          router.push({ path: '/' })
        }
      })
      return
    }
    // 2、店铺状态为0(停业中)时，当店铺超过签约有效期，用户进入店铺提示：商家已暂停未营业
    if (today > contractEndTime) {
      ElMessage({
        type: 'warning',
        message: $t('collection.storeReviewTips5'),
        duration: 1000,
        onClose: () => {
          router.push({ path: '/' })
        }
      })
      return
    }
  }
  // 已下线
  if (shopStatus === 2 || shopStatus === 3) {
    ElMessage({
      type: 'warning',
      message: $t('collection.storeReviewTips3'),
      duration: 1000,
      onClose: () => {
        router.push({ path: '/' })
      }
    })
  }
}

/**
 * 跳转公告详情
 */
const toNewsDet = (id) => {
  router.push({
    path: '/notice-detail',
    query: {
      id,
      shopId: shopId.value,
      shopName: shopInfo.value.shopName
    }
  })
}

/**
 * 跳转公告列表
 */
const toNewsList = () => {
  router.push({
    path: '/notice-list',
    query: {
      shopId: shopId.value,
      shopName: shopInfo.value.shopName
    }
  })
}

/**
 * 获取店铺信息
 */
const getInfo = () => {
  if (!route.query.sid) {
    shopId.value = shopInfo.value.shopId
  }
  if (categoryId.value) {
    categoryList.value.forEach(category => {
      if (categoryId.value === Number(category.categoryId)) {
        categoryName.value = category.categoryName
      }
    })
  }
}

const isCollection = ref(false)
/**
 * 获取用户是否收藏此店铺
 */
const getUserCollection = () => {
  http.get('/p/shop/collection/isCollection', {
    params: {
      shopId: shopId.value
    }
  }).then(({ data }) => {
    isCollection.value = data
  })
}

/**
 * 收藏店铺/取消收藏
 */
const shopCollection = () => {
  http.post('/p/shop/collection/addOrCancel', shopId.value).then(({ data }) => {
    if (data) {
      ElMessage({
        message: $t('prodDetail.collectionSuccess'),
        type: 'success',
        duration: 1000
      })
    } else {
      ElMessage({
        message: $t('prodDetail.uncollected'),
        duration: 1000
      })
    }
    getUserCollection()
  })
}

/**
 * 去到首页
 */
const homePage = () => {
  if (shopId.value) {
    router.push({
      path: '/shop-index',
      query: {
        sid: shopId.value
      }
    })
  } else {
    ElMessage({
      type: 'warning',
      message: $t('userCenter.theStoreOffline')
    })
  }
}

/**
 * 查询该分类下的商品
 */
const getProdListByCategory = (categoryIdPar) => {
  if (shopId.value) {
    if (!categoryIdPar) {
      router.push({
        path: '/shop-index',
        query: {
          sid: shopId.value
        }
      })
    } else {
      router.replace({
        path: route.path,
        query: {
          sid: shopId.value,
          cid: categoryIdPar
        }
      })
    }
  } else {
    ElMessage({
      type: 'warning',
      message: $t('userCenter.theStoreOffline')
    })
  }
}

/**
 * 搜索商品/查询指定分页下的商品
 */
const getSearchProdPage = (currentPar) => {
  prodName.value = prodName.value ? prodName.value.trim() : ''
  let path = {
    path: '/shop-prod-list',
    query: {
      sid: shopId.value,
      c: currentPar
    }
  }
  // 通过商品名称搜索
  if (prodName.value) {
    path = {
      path: '/shop-prod-list',
      query: {
        sid: shopId.value,
        c: currentPar,
        pn: prodName.value
      }
    }
  }
  // 在分类查询的基础上查询/分页
  if (categoryId.value) {
    path = {
      path: '/shop-prod-list',
      query: {
        sid: shopId.value,
        c: currentPar,
        pn: prodName.value,
        cid: categoryId.value
      }
    }
  }
  getPageData(path.query)
}

/**
 * 跳转到商品
 */
const toProdDetail = (prodId, newWindow) => {
  const params = {
    prodId,
    lang: langStore.locale
  }
  const newPage = router.resolve({
    path: '/detail',
    query: params
  })
  if (newWindow) {
    newWindow.location.href = newPage.href
  } else {
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  }
}

/**
 * 价格处理
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

</script>

<style lang="scss" scoped>
@use "../shop-index/index";
</style>

<style lang="scss" scoped>
@use "index";
</style>
